package com.plian.system.controller.qg.guarantee;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.plian.Tools.Func;
import com.plian.Tools.StringPool;
import com.plian.Tools.StringUtil;
import com.plian.Tools.TokenUtil;
import com.plian.Tools.base.BaseController;
import com.plian.Tools.pagedata.PageData;
import com.plian.system.annotation.LogOperation;
import com.plian.system.common.status.CustomCode;
import com.plian.system.config.Resubmit;
import com.plian.system.constant.sys.FormStatusConstant;
import com.plian.system.dto.qg.guarantee.PropertyGuaranteeExecuteDTO;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeApply;
import com.plian.system.entity.qg.guarantee.PropertyGuaranteeExecute;
import com.plian.system.model.CommonCode;
import com.plian.system.model.ListResult;
import com.plian.system.model.ObjResult;
import com.plian.system.model.R;
import com.plian.system.mybatis.search.SearchEntity;
import com.plian.system.mybatis.search.SearchParamEntiy;
import com.plian.system.mybatis.search.TokenSearch;
import com.plian.system.mybatis.support.Condition;
import com.plian.system.mybatis.support.Query;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeApplyService;
import com.plian.system.service.qg.guarantee.IPropertyGuaranteeExecuteService;
import com.plian.system.service.wf.FormWorkflowService;
import com.plian.system.vo.qg.guarantee.PropertyGuaranteeExecuteVO;
import com.plian.system.vo.report.ReportReturnVO;
import com.plian.system.wrapper.qg.guarantee.PropertyGuaranteeExecuteWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Optional;

/**
 * 企业担保执行主表 控制器
 *
 * @author jianglei
 * @since 2019-10-24
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("api/propertyguaranteeexecute")
public class PropertyGuaranteeExecuteController extends BaseController {

    private IPropertyGuaranteeExecuteService propertyGuaranteeExecuteService;

    private IPropertyGuaranteeApplyService propertyGuaranteeApplyService;

    private PropertyGuaranteeExecuteWrapper propertyGuaranteeExecuteWrapper;

    private FormWorkflowService formWorkflowService;

    /**
     * 详情
     */
    @PostMapping("/detail")
    public R<PropertyGuaranteeExecuteVO> detail(@Valid @RequestBody PropertyGuaranteeExecute propertyGuaranteeExecute) {
        PropertyGuaranteeExecuteVO propertyGuaranteeExecuteVO = propertyGuaranteeExecuteWrapper
                .entityToVO(propertyGuaranteeExecuteService.getOne(Condition.getQueryWrapper(propertyGuaranteeExecute)));
        PropertyGuaranteeApply propertyGuaranteeApply = propertyGuaranteeApplyService.getById(propertyGuaranteeExecuteVO.getUpstreamCodeId());
        if (Optional.ofNullable(propertyGuaranteeApply).isPresent()) {
            propertyGuaranteeExecuteVO.setGuaranteeTotal(propertyGuaranteeApply.getGuaranteeTotal() == null ? new BigDecimal(0) : propertyGuaranteeApply.getGuaranteeTotal());
            propertyGuaranteeExecuteVO.setGuaranteeRemain(propertyGuaranteeApply.getGuaranteeRemain() == null ? new BigDecimal(0) : propertyGuaranteeApply.getGuaranteeRemain());
            propertyGuaranteeExecuteVO.setTotalLoanAmount(propertyGuaranteeApply.getTotalLoanAmount() == null ? new BigDecimal(0) : propertyGuaranteeApply.getTotalLoanAmount());
        }
        propertyGuaranteeExecuteVO.setApplyId(propertyGuaranteeExecuteVO.getUpstreamCodeId());
        propertyGuaranteeExecuteVO.setExecuteId(propertyGuaranteeExecuteVO.getId());
        propertyGuaranteeExecuteVO.setExecuteCode(propertyGuaranteeExecute.getCode());
        return R.data(propertyGuaranteeExecuteVO);
    }

    /**
     * 分页 企业担保执行主表
     */
    @PostMapping("/list")
    public ListResult<PropertyGuaranteeExecuteVO> list(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<PropertyGuaranteeExecute> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new PropertyGuaranteeExecute()), entityList
        );
        TokenSearch<PropertyGuaranteeExecute> tokenSearch = new TokenSearch<>();
        tokenSearch.addTokenQuery(queryWrapper, query);

        IPage<PropertyGuaranteeExecute> pages = propertyGuaranteeExecuteService.page(Condition.getPage(query), queryWrapper);
        List<PropertyGuaranteeExecuteVO> propertyGuaranteeExecuteVOS = propertyGuaranteeExecuteWrapper.entityToVO(pages.getRecords());
        ListResult<PropertyGuaranteeExecuteVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(propertyGuaranteeExecuteVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;
    }


    /**
     * 新增或修改 企业担保执行主表
     */
    @PostMapping("/submit")
    @LogOperation("企业担保执行-提交")
    @Resubmit(delaySeconds = 0)
    public ObjResult submit(@Valid @RequestBody PropertyGuaranteeExecute propertyGuaranteeExecute) {
        String result = propertyGuaranteeExecuteService.checkSubmit(propertyGuaranteeExecute);
        if (StringUtil.isNotBlank(result)) {
            return new ObjResult(CustomCode.builder().message(result).code(1999).success(false).build());
        }
        PropertyGuaranteeExecute old = propertyGuaranteeExecuteService.getById(propertyGuaranteeExecute.getId());
        result = propertyGuaranteeApplyService.checkExecute(propertyGuaranteeExecute.getUpstreamCodeId(), old, propertyGuaranteeExecute);
        if (StringUtil.isNotBlank(result)) {
            return new ObjResult(CustomCode.builder().message(result).code(1999).success(false).build());
        }
        ObjResult objResult = propertyGuaranteeExecuteService.submit(propertyGuaranteeExecute)
                ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
        HashMap<String, Object> processVariable = new HashMap<>();
        formWorkflowService.startProcessAndSimulate(String.valueOf(propertyGuaranteeExecute.getId()), propertyGuaranteeExecute.getFormType(), processVariable);
        return objResult;

    }


    /**
     * 删除 企业担保执行主表
     */
    @PostMapping("/remove")
    @LogOperation("企业担保执行-删除")
    public ObjResult remove(@RequestBody PageData pd) {
        List<String> ids = (List<String>) pd.get("ids");
        for (String id : ids) {
            PropertyGuaranteeExecute propertyGuaranteeExecute = propertyGuaranteeExecuteService.getById(Long.valueOf(id));
            propertyGuaranteeApplyService.checkExecute(propertyGuaranteeExecute.getUpstreamCodeId(), propertyGuaranteeExecute, null);
        }
        return propertyGuaranteeExecuteService.deleteLogic(Func.toLongList(StringUtils.join(ids, StringPool.COMMA)))
                ? new ObjResult(CommonCode.SUCCESS) : new ObjResult(CommonCode.FAIL);
    }

    /**
     * 企业相关担保金额分析
     */
    @PostMapping("/guaranteeAmountAnalysis")
    public ObjResult guaranteeAmountAnalysis(@Valid @RequestBody(required = false) PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO) {
        ObjResult objResult;
        try {
            ReportReturnVO reportReturnVO = propertyGuaranteeExecuteService.guaranteeAmountAnalysis(propertyGuaranteeExecuteDTO);
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (Optional.ofNullable(reportReturnVO).isPresent()) {
                PageData pd = new PageData();
                pd.put("charts", reportReturnVO.getCharts());
                objResult.setPageData(pd);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }

        return objResult;
    }

    /**
     * 企业相关被担保金额分析
     */
    @PostMapping("/guaranteedAmountAnalysis")
    public ObjResult guaranteedAmountAnalysis(@Valid @RequestBody(required = false) PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO) {
        ObjResult objResult;
        try {
            ReportReturnVO reportReturnVO = propertyGuaranteeExecuteService.guaranteedAmountAnalysis(propertyGuaranteeExecuteDTO);
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (Optional.ofNullable(reportReturnVO).isPresent()) {
                PageData pd = new PageData();
                pd.put("charts", reportReturnVO.getCharts());
                objResult.setPageData(pd);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }

        return objResult;
    }

//	/**
//	 * 输出excel前置
//	 */
//	@PostMapping("/preexport")
//	public R<String> preexport(@RequestBody String jsonString){
//		String md5= DigestUtil.hmacMd5Hex(jsonString, SecureUtil.getUserId() +"");
//		File file=propertyGuaranteeExecuteService.exportExcel(JSON.parseObject(jsonString));
//		return  R.data(PropertyGuaranteeExecuteCache.putJsonByKey(md5,file));
//	}
//
//	/**
//	 * 输出excel
//	 */
//	@GetMapping("/export/{key}")
//	@ApiOperationSupport(order = 7)
//	@ApiOperation(value = "输出", notes = "传入json")
//	public ResponseEntity<FileSystemResource> export(@PathVariable String key) {
//		return FileTools.exportFile(PropertyGuaranteeExecuteCache.getJsonByKey(key),"企业担保执行");
//	}

    /**
     * 执行情况汇总表
     */
    @PostMapping("/getExecutes")
    public ObjResult getExecutes(@Valid @RequestBody(required = false) PropertyGuaranteeExecuteDTO propertyGuaranteeExecuteDTO) {
        ObjResult objResult;
        try {
            ReportReturnVO reportReturnVO = propertyGuaranteeExecuteService.getExecutes(propertyGuaranteeExecuteDTO);
            objResult = new ObjResult(CommonCode.SUCCESS);
            if (Optional.ofNullable(reportReturnVO).isPresent()) {
                PageData pd = new PageData();
                pd.put("grids", reportReturnVO.getGrids());
                objResult.setPageData(pd);
            }
        } catch (Exception e) {
            log.error(ExceptionUtils.getFullStackTrace(e));
            objResult = new ObjResult(CommonCode.ERROR);
            return objResult;
        }

        return objResult;
    }

    /**
     * 担保结束
     *
     * @param id
     * @return
     */
    @GetMapping("/executeFinish/{id}")
    public ObjResult executeFinish(@PathVariable Long id) {
        return propertyGuaranteeExecuteService.executeFinish(id);
    }

    @PostMapping("/refList")
    public ListResult<PropertyGuaranteeExecuteVO> refList(@Valid @RequestBody Query query) {
        if (query.getAscs() == null && query.getDescs() == null) {
            query.setDescs("create_time");
        }
        List<SearchEntity> entityList = query.getSearch();
        QueryWrapper<PropertyGuaranteeExecute> queryWrapper = SearchParamEntiy.getQueryWrapper(
                Condition.getQueryWrapper(new PropertyGuaranteeExecute()), entityList
        );
        queryWrapper.eq("create_company_id", TokenUtil.getTokenOrgId());
        queryWrapper.eq("status", FormStatusConstant.FINISH);
        queryWrapper.ne("is_end", 2);

        IPage<PropertyGuaranteeExecute> pages = propertyGuaranteeExecuteService.page(Condition.getPage(query), queryWrapper);
        List<PropertyGuaranteeExecuteVO> propertyGuaranteeExecuteVOS = propertyGuaranteeExecuteWrapper.entityToVO((pages).getRecords());

        ListResult<PropertyGuaranteeExecuteVO> listResult = new ListResult<>(CommonCode.SUCCESS);
        listResult.setList(propertyGuaranteeExecuteVOS);
        listResult.setTotal(Long.valueOf(pages.getTotal()).intValue());
        return listResult;

    }

}
